using UnityEngine;
using QFramework;
using QAssetBundle;
using System.Collections;
using System.Linq;
using System.Collections.Generic;

namespace ProjectSurviver
{
	public partial class GetAllExp : GamePlayObject
	{
		static IEnumerator FlyToPlayerStart()
		{
			IEnumerable<PowerUp> exps = FindObjectsByType<Exp>(FindObjectsInactive.Exclude, FindObjectsSortMode.None);
			IEnumerable<PowerUp> coins = FindObjectsByType<Coin>(FindObjectsInactive.Exclude, FindObjectsSortMode.None);

			int count = 0;
			foreach (var powerup in exps.Concat(coins)
			.OrderByDescending(e => e.IsScreen)
			.ThenBy(e => e.Distance2D(Player.Default)))
			{
				if(powerup.IsScreen)
				{
					if(count > 10)
					{
						count = 0;
						yield return new WaitForEndOfFrame(); // 等待下一帧
					}
				}
				else
				{
					if(count > 2)
					{
						count = 0;
						yield return new WaitForEndOfFrame(); // 等待下一帧
					}
				}

				count++;	
				ActionKit.OnUpdate.Register(() => // 注册一个更新事件
				{
					var player = Player.Default; // 获取主角
					if(player)
					{
						powerup.transform.Translate(player.NormalizedDirection2DFrom(powerup).normalized * Time.deltaTime * 5f); // 移动
					}
				}).UnRegisterWhenGameObjectDestroyed(powerup); // 注册一个销毁事件
			}
		}

        public override Collider2D Collider2D => SelfCollider2D;

        void OnTriggerEnter2D(Collider2D other)
        {
			// 如果碰到CollectableArea，就销毁自己
            if(other.GetComponent<CollectableArea>())
			{
				// 生成100个Coin
				PowerUpManager.Default.StartCoroutine(FlyToPlayerStart());
				AudioKit.PlaySound(Sfx.GETALLEXP);
				this.DestroyGameObjGracefully();
			}
        }
    }
}
